package com.tchepannou.limbe.web.servlet;

import com.tchepannou.limbe.engine.ConfigurationException;
import com.tchepannou.limbe.engine.Engine;
import com.tchepannou.limbe.engine.EngineConfigurator;
import com.tchepannou.util.MimeUtil;
import com.tchepannou.util.StringUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 * This is the web servlet
 *
 * @author Herve Tchepannou
 */
@SuppressWarnings("serial")
public class LimbeServlet
    extends HttpServlet
{
    //-- Static Attribute
    private static final Logger LOG = Logger.getLogger (LimbeServlet.class.getName());
    private static final String UTF_8 = "utf-8";
    public static final String ENGINE_KEY = "com.tchepannou.limbe.engine";

    //-- Attribute
    private Engine _engine;

    //-- HttpServlet overrides
    @Override
    protected void service (HttpServletRequest req, HttpServletResponse resp)
        throws ServletException,
               IOException
    {
        /* IMPORTANT !!!! set the charset ! */
        String charset = UTF_8;
        req.setCharacterEncoding (charset);

        String path = req.getPathInfo ();
        String mime = path != null ? MimeUtil.getInstance ().getMimeTypeByFile (path) : null;
        if (StringUtil.isEmpty (mime))
        {
            mime = MimeUtil.HTML;
        }
        resp.setContentType (mime + ";charset=" + charset);
        resp.setCharacterEncoding (charset);


        /* Handle the request */
        _engine.getActionContainer ().service (req, resp);
    }

    @Override
    public void destroy ()
    {
        LOG.info ("Destroying");

        _engine.destroy ();
        getServletContext().removeAttribute(ENGINE_KEY);
        super.destroy ();

        LOG.info ("Destroyed");
    }

    @Override
    public void init (ServletConfig config)
        throws ServletException
    {
        LOG.info ("Initializing");

        super.init (config);

        ServletContext sc = config.getServletContext ();
        EngineConfigurator cfg = new EngineConfigurator ();
        
        try
        {
            /* System properties */
//            LOG.info ("System properties");
//            Properties props = System.getProperties ();
//            for (String name : props.stringPropertyNames ())
//            {
//                LOG.info (" " + name + "=" + props.getProperty (name));
//            }

            LOG.info("Get Engine Instance");
            _engine = new Engine();
            getServletContext().setAttribute(ENGINE_KEY, _engine);

            /* configure */
            LOG.info ("Configuring Engine");
            cfg.configure (_engine, sc);

            /* init */
            LOG.info ("Initializing Engine");
            _engine.init (sc);

            LOG.info ("Initialized");
        }
        catch ( ConfigurationException e )
        {
            LOG.log (Level.SEVERE, "Configuration error. Initialization failed", e);
            throw new ServletException ("Configuration failed", e);
        }
    }
}
